//
//  ViewController.m
//  coreBlueTooth
//
//  Created by 刘禹晨 on 5/14/16.
//  Copyright © 2016 刘禹晨. All rights reserved.
//

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import <AVFoundation/AVFoundation.h>
#import <SDAutoLayout/SDAutoLayout.h>
#import "ZigbeeModel.h"
#import "NodeCell.h"
#import "CBHelper.h"
#import "JSONKit/JSONKit.h"
#import "SocketManager.h"
#import "Mode.h"
#import "MenuView.h"
#import "CocoaAsyncSocket/GCDAsyncSocket.h"
#import "AppDelegate.h"

#define kW [UIScreen mainScreen].bounds.size.width
#define kH [UIScreen mainScreen].bounds.size.height

static NSString *armCommand =    @"11SSSNSNNNN&F";
static NSString *disarmCommand = @"11SNSSSNNNN&F";

@interface ViewController () <BLEManagerDelegate,UITableViewDelegate,UITableViewDataSource,SocketManagerDelegate>


{
    NSMutableData *resultData;
    NSString *recvValue;
    CBPeripheral *currectPeripheral;
    CBCharacteristic *writeCharacter;
    
    BOOL isReceived;
    UINavigationItem *_uiNavigationItem;
    UITableView *_nodeTableView;
    BOOL isExist;
    UILabel *rightButton;
    SystemSoundID soundID;
    NSMutableDictionary *nodeDict;
    BOOL isCoordinator;
    CBHelper *_cbHelper;
    Mode *_mode;
    Mode *_mode2;
    GCDAsyncSocket *socket;
    ZigbeeModel *currectZigbee;
    AppDelegate *delegate;
    NSTimer *_notificationTimer;
    BOOL isTimerStart;
    
}

@property (strong, nonatomic) BLEManager *bleManager;
@property (strong, nonatomic) UITextView *uitextview;

@property (strong, nonatomic) UIButton *wirteButton;
@property (strong, nonatomic) UINavigationBar *navigationBar;

@property (strong, nonatomic) UIButton *allArmButton;
@property (strong, nonatomic) UIButton *allDisarmButton;

@property (strong,nonatomic) AVAudioPlayer *alarm;
@property (copy,nonatomic) NSString *message;

@property (strong, nonatomic) SocketManager *socketManager;



@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _mode = [Mode instance];
    _mode.mode = @"BLE";
    self.bleManager = [BLEManager instance];
    self.socketManager = [SocketManager instance];
    [self selectMode:_mode.mode];
    [_mode addObserver:self forKeyPath:@"mode" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"changeMode"];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    _zigbeeArray = [NSMutableArray array];
    resultData = [NSMutableData data];
    //[self initNavigationBar];
    [self initNodeTableView];
    [self initHeaderView];
    [self.view addSubview:_nodeTableView];
    //[self.view addSubview:_navigationBar];
    [self initWAV];
    nodeDict = [NSMutableDictionary dictionary];
    isReceived = NO;
    isExist = NO;
    isCoordinator = NO;
    isTimerStart = NO;
    _cbHelper = [CBHelper sharedInstance];
    _cbHelper.AlarmCount = 0;
    self.navigationItem.title = @"节点列表";
    UIBarButtonItem *leftMenuButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"list_menu"] style:UIBarButtonItemStylePlain target:self action:@selector(openLeftMenu:)];
    self.navigationItem.leftBarButtonItem = leftMenuButton;
    delegate = [UIApplication sharedApplication].delegate;
    [_cbHelper addObserver:self forKeyPath:@"arrayCount" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"refereshWebView"];
    [_cbHelper addObserver:self forKeyPath:@"AlarmCount" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"alarmCountChange"];
    
    UILongPressGestureRecognizer *gestureLongPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(gestureLongPress:)];
    gestureLongPress.minimumPressDuration = 1;
    [_nodeTableView addGestureRecognizer:gestureLongPress];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Special Methods
-(void)selectMode:(NSString*) mode
{
    if ([mode isEqualToString:@"BLE"])
    {
        if(self.socketManager != nil)
        {
            [self.socketManager socketDisconnect];
        }
        for (ZigbeeModel *obj in self.zigbeeArray)
        {
            @try{
                [obj removeObserver:self forKeyPath:@"AlterState"];
            }
            @catch (NSException *e){
                NSLog(@"%@",e);
            }
        }
        [self.zigbeeArray removeAllObjects];
        [_nodeTableView reloadData];
        isCoordinator = NO;
        [self.bleManager setup];
        [self.bleManager scan];
        self.bleManager.delegate = self;
    }else
    {
        if(self.bleManager != nil)
        {
            [self.bleManager BLEDisconnect];
        }
        for (ZigbeeModel *obj in self.zigbeeArray)
        {
            @try{
                [obj removeObserver:self forKeyPath:@"AlterState"];
            }
            @catch (NSException *e){
                NSLog(@"%@",e);
            }
        }
        [self.zigbeeArray removeAllObjects];
        [_nodeTableView reloadData];
        isCoordinator = NO;
        [self.socketManager initSocket];
        [self.socketManager socketConnectHost];
        self.socketManager.delegate = self;
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    NSLog(@"ViewController Did Appear");
    [delegate.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [delegate.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
}

-(void)viewWillDisappear:(BOOL)animated
{
    
    NSLog(@"ViewController Will DisAppear");
    [delegate.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
    [delegate.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeNone];
}

-(void)openLeftMenu:(id)sender
{
    [delegate.drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];//左侧打开关闭侧边栏方法
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"%@",context);
    id _context = (__bridge id)context;
    NSString *whichKVO = [NSString stringWithFormat:@"%@",_context];
    if([whichKVO isEqualToString:@"changeMode"]){
        NSString *newMode = [change valueForKey:@"new"];
        [self selectMode:newMode];
    }
    if([whichKVO isEqualToString:@"refereshWebView"])
    {
        NSLog(@"viewController Referesh");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateWebView" object:nil userInfo:nil];
    }
    if([whichKVO isEqualToString:@"updateNodeState"])
    {
        NSLog(@"viewController Update");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateWebView" object:nil userInfo:nil];
        [object removeObserver:self forKeyPath:@"AlterState"];
        ZigbeeModel *zigbee = (ZigbeeModel *)object;
        [zigbee addObserver:self forKeyPath:@"AlterState" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"updateNodeState"];
    }
    if([whichKVO isEqualToString:@"alarmCountChange"])
    {
        NSLog(@"Alarm Count Changed");
        if([UIApplication sharedApplication].applicationState == UIApplicationStateBackground && _cbHelper.AlarmCount != 0)
        {
            [self registerLocalNotification:@"入侵警报！入侵警报！"];
        }
    }
}

#pragma mark - UIInit Methods
-(void)initWrite
{
    _wirteButton = [[UIButton alloc]init];
    [_wirteButton setTitle:@"布防" forState:UIControlStateNormal];
    [_wirteButton setBackgroundColor:[UIColor brownColor]];
    [_wirteButton setFrame:CGRectMake(kW/2, kH/2, 50, 30)];
    [_wirteButton addTarget:self action:@selector(writeValue:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_wirteButton];
}

- (void)gestureLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint tmpPointTouch = [gestureRecognizer locationInView:_nodeTableView];
    NSInteger selectRow;
    if (gestureRecognizer.state ==UIGestureRecognizerStateBegan) {
        NSIndexPath *indexPath = [_nodeTableView indexPathForRowAtPoint:tmpPointTouch];
        if (indexPath == nil) {
            NSLog(@"not tableView");
        }else{
            selectRow = [indexPath row];
            NodeCell *cell = [_nodeTableView cellForRowAtIndexPath:indexPath];
            cell.backgroundColor = [UIColor colorWithRed:0.792 green:0.792 blue:0.792 alpha:1.0];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"当前节点Mac地址" message:cell.model.NodeMac preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *defult = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                cell.backgroundColor = [UIColor whiteColor];
            }];
            [alert addAction:defult];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
}




-(void)initNavigationBar
{
    _navigationBar = [[UINavigationBar alloc]init];
    _navigationBar.frame = CGRectMake(0,0,kW,64);
    _navigationBar.barTintColor = [[UIColor new] initWithRed:255.0f/255.0f green:73.0f/255.0f blue:64.0f/255.0f alpha:1.0f];
    _navigationBar.translucent = NO;
    _uiNavigationItem = [[UINavigationItem alloc] initWithTitle:@"节点列表"];
//    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"一键布防" style:UIBarButtonItemStylePlain target:self action:@selector(changeMode:)];
//    _uiNavigationItem.rightBarButtonItem = right;
    _navigationBar.tintColor = [UIColor whiteColor];
    NSMutableDictionary *barsytle = [NSMutableDictionary dictionary];
    [barsytle setObject:[UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.0f] forKey:NSForegroundColorAttributeName];
    [_navigationBar setTitleTextAttributes:barsytle];
    [_navigationBar pushNavigationItem:_uiNavigationItem animated:NO];

}

-(void)initNodeTableView
{
    _nodeTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 48) style:UITableViewStylePlain];
    //UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kW, 44.0)];
    //[_nodeTableView setTableHeaderView:header];
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kW, 120.0)];
    [_nodeTableView setTableFooterView:footer];
    //_nodeTableView.separatorStyle = NO;
    [_nodeTableView registerClass:[NodeCell class] forCellReuseIdentifier:@"NodeCell"];
    _nodeTableView.dataSource = self;
    _nodeTableView.delegate = self;
}

-(void)initHeaderView
{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kW, 44.0)];
    [self.view addSubview:header];
    _allArmButton = [[UIButton alloc]init];
    UIImage *armImage = [CBHelper imageWithColor:[[UIColor new] initWithRed:255.0f/255.0f green:73.0f/255.0f blue:64.0f/255.0f alpha:1.0f] size:CGSizeMake(kW,44)];
    //_allArmButton.backgroundColor = [[UIColor new] initWithRed:255.0f/255.0f green:73.0f/255.0f blue:64.0f/255.0f alpha:1.0f];
    [_allArmButton setBackgroundImage:armImage forState:UIControlStateNormal];
    [_allArmButton setTitle:@"一键布防" forState:UIControlStateNormal];
    _allArmButton.clipsToBounds = YES;
    _allArmButton.layer.cornerRadius = 5;
    _allArmButton.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [header addSubview:_allArmButton];
    CGFloat width = kW/2 - 8*2;
    _allArmButton.sd_layout.heightIs(29).widthIs(width).centerYEqualToView(header).leftSpaceToView(header,12);
    
    _allDisarmButton = [[UIButton alloc]init];
    //_allDisarmButton.backgroundColor = [UIColor grayColor];
    UIImage *disArmImage = [CBHelper imageWithColor:[[UIColor new] initWithRed:254.0f/255.0f green:196.0f/255.0f blue:46.0f/255.0f alpha:1.0f] size:CGSizeMake(kW,44)];
    [_allDisarmButton setBackgroundImage:disArmImage forState:UIControlStateNormal];
    [_allDisarmButton setTitle:@"一键撤防" forState:UIControlStateNormal];
    _allDisarmButton.clipsToBounds = YES;
    _allDisarmButton.layer.cornerRadius = 5;
    _allDisarmButton.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [header addSubview:_allDisarmButton];
    _allDisarmButton.sd_layout.heightIs(29).widthIs(width).centerYEqualToView(header).rightSpaceToView(header,12);
    
    [_allArmButton addTarget:self action:@selector(writeArmValue:) forControlEvents:UIControlEventTouchUpInside];
    [_allDisarmButton addTarget:self action:@selector(writeDisArmValue:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)writeArmValue:(id)sender
{
    NSString *bChar = @"#FFFFFFFFFFFFFFFFFFFF11SSSNSNNNN&F";
    NSData *bCharData = [bChar dataUsingEncoding:NSASCIIStringEncoding];
    if([_mode.mode isEqualToString:@"BLE"]){
        [currectPeripheral writeValue:bCharData forCharacteristic:writeCharacter type:CBCharacteristicWriteWithoutResponse];
    }else{
        [socket writeData:bCharData withTimeout:5 tag:1];
    }
}

-(void)writeDisArmValue:(id)sender
{
    NSString *bChar = @"#FFFFFFFFFFFFFFFFFFFF11SNSSSNNNN&F";
    NSData *bCharData = [bChar dataUsingEncoding:NSASCIIStringEncoding];
    if([_mode.mode isEqualToString:@"BLE"]){
        [currectPeripheral writeValue:bCharData forCharacteristic:writeCharacter type:CBCharacteristicWriteWithoutResponse];
    }else{
        [socket writeData:bCharData withTimeout:5 tag:1];
    }
}

-(void)initWAV
{
    
    NSString *alarmSoundPath = [[NSBundle mainBundle] pathForResource:@"ALARM" ofType:@"wav"];
    NSURL *soundURL = [[NSURL alloc] initFileURLWithPath:alarmSoundPath];
    //    soundID = 0;
    //    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(soundURL), &soundID);
    NSError *playerError;
    self.alarm = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&playerError];
    
    [self.alarm setNumberOfLoops:-1];
    [self.alarm setVolume:1];
    [self.alarm prepareToPlay];
}

#pragma mark - TableView delegate
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *TableSampleIdentifier = @"test";

    NodeCell *cell = [tableView dequeueReusableCellWithIdentifier:
            TableSampleIdentifier];
    if(!cell){
        cell = [[NodeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
    }

    ZigbeeModel *model = self.zigbeeArray[indexPath.row];
    cell.model = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //cell.text =@"hahaha";
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Class currentClass = [NodeCell class];

    ZigbeeModel *model = self.zigbeeArray[indexPath.row];

    // 推荐使用此普通简化版方法（一步设置搞定高度自适应，性能好，易用性好）
    return [_nodeTableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:currentClass contentViewWidth:[self cellContentViewWith]];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.zigbeeArray count];
}


- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;

    // 适配ios7
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}

#pragma mark  core method

//- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
//
//    // 布防
//    UITableViewRowAction *noArmAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"布防" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        //事件
//        NSInteger row = indexPath.row;
//        currectZigbee = self.zigbeeArray[row];
//        NSString *firstChar = @"#";
//        NSString *nodeAddress = [firstChar stringByAppendingString:currectZigbee.NodeNetworkAddress];
//        NSString *nodeAddressAndMac = [nodeAddress stringByAppendingString:currectZigbee.realMac];
//        NSString *result = [nodeAddressAndMac stringByAppendingString:armCommand];
//        NSLog(@"%@",result);
//        NSData *bCharData = [result dataUsingEncoding:NSASCIIStringEncoding];
//        if([_mode.mode isEqualToString:@"BLE"]){
//            [currectPeripheral writeValue:bCharData forCharacteristic:writeCharacter type:CBCharacteristicWriteWithoutResponse];
//        }else{
//            [socket writeData:bCharData withTimeout:5.0 tag:1];
//        }
//    }];
//
//    //撤防
//    UITableViewRowAction *noDisarmAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"撤防" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        //事件
//        NSInteger row = indexPath.row;
//        currectZigbee = self.zigbeeArray[row];
//        NSString *firstChar = @"#";
//        NSString *nodeAddress = [firstChar stringByAppendingString:currectZigbee.NodeNetworkAddress];
//        NSString *nodeAddressAndMac = [nodeAddress stringByAppendingString:currectZigbee.realMac];
//        NSString *result = [nodeAddressAndMac stringByAppendingString:disarmCommand];
//        NSLog(@"%@",result);
//        NSData *bCharData = [result dataUsingEncoding:NSASCIIStringEncoding];
//        if([_mode.mode isEqualToString:@"BLE"]){
//            [currectPeripheral writeValue:bCharData forCharacteristic:writeCharacter type:CBCharacteristicWriteWithoutResponse];
//        }else{
//            [socket writeData:bCharData withTimeout:5.0 tag:1];
//        }
//
//    }];
//
//    noArmAction.backgroundColor = [[UIColor new] initWithRed:255.0f/255.0f green:73.0f/255.0f blue:64.0f/255.0f alpha:1.0f];
//    noDisarmAction.backgroundColor = [UIColor blackColor];
//    return @[noArmAction, noDisarmAction];
//}




#pragma mark - BLE Methods

-(void)didReadvalue {
    writeCharacter = self.bleManager.cbCharacteristic;
    NSData *recvData = self.bleManager.cbCharacteristic.value;
    currectPeripheral = self.bleManager.currentPeripheral;

    if(recvData.length != 15)
    {
        [resultData appendData:recvData];
    }else{
        [resultData appendData:recvData];
        isReceived = YES;
    }
    if(isReceived == YES)
    {
        recvValue = [[NSString alloc] initWithData:resultData encoding:NSASCIIStringEncoding];
        NSArray *array = [recvValue componentsSeparatedByString:@"\n"];
        for(NSString *value in array)
        {
            if(value.length > 2){
                [self vailedValue:value];
            }
        }
        [resultData setLength:0];
        isReceived = NO;
        NSLog(@"%@",recvValue);
    }
}

#pragma mark - WiFi Methods
-(void)didSocketConnected
{
    socket = self.socketManager.socket;
}
-(void)didReadvalue:(NSData *)data
{
    recvValue = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSArray *array = [recvValue componentsSeparatedByString:@"\n"];
    for(NSString *value in array)
    {
        if(value.length > 2){
            [self vailedValue:value];
        }
    }
    //isReceived = NO;
    NSLog(@"%@",recvValue);
}

#pragma mark - Utils

-(void)writeValue:(id)sender
{
    NSString *bChar = @"#FFFFFFFFFFFFFFFFFFFF11SSSNSNNNN&F";
    NSData *bCharData = [bChar dataUsingEncoding:NSASCIIStringEncoding];
        //[self createNodeAndChilde:_zigbeeArray]
    if([_mode.mode isEqualToString:@"BLE"]){
        [currectPeripheral writeValue:bCharData forCharacteristic:writeCharacter type:CBCharacteristicWriteWithoutResponse];
    }else{
        [socket writeData:bCharData withTimeout:5 tag:1];
    }
}

-(void)vailedValue:(NSString*) values
{
    NSString *firstChar = [values substringWithRange:NSMakeRange(0, 1)];
    if(![firstChar isEqualToString:@"#"] && values.length != 55)
    {
        NSLog(@"ERROR DATA");
        return;
    }
    ZigbeeModel *zigbee = [[ZigbeeModel alloc]init];
    NSString *networkAddress = [[NSString alloc] init];
    networkAddress = [[values substringWithRange:NSMakeRange(2, 4)] uppercaseString];
    NSMutableString *nodeMac = [[NSMutableString alloc] init];
    [nodeMac appendString:[[values substringWithRange:NSMakeRange(6,2)] uppercaseString]];
    [nodeMac appendString:@":"];
    [nodeMac appendString:[[values substringWithRange:NSMakeRange(8,2)] uppercaseString]];
    [nodeMac appendString:@":"];
    [nodeMac appendString:[[values substringWithRange:NSMakeRange(10,2)] uppercaseString]];
    [nodeMac appendString:@":"];
    [nodeMac appendString:[[values substringWithRange:NSMakeRange(12,2)] uppercaseString]];
    [nodeMac appendString:@":"];
    [nodeMac appendString:[[values substringWithRange:NSMakeRange(14,2)] uppercaseString]];
    [nodeMac appendString:@":"];
    [nodeMac appendString:[[values substringWithRange:NSMakeRange(16,2)] uppercaseString]];
    [nodeMac appendString:@":"];
    [nodeMac appendString:[[values substringWithRange:NSMakeRange(18,2)] uppercaseString]];
    [nodeMac appendString:@":"];
    [nodeMac appendString:[[values substringWithRange:NSMakeRange(20,2)] uppercaseString]];
    NSString *realMac = [values substringWithRange:NSMakeRange(6,16)];
    for(ZigbeeModel *obj in _zigbeeArray)
    {
        if([obj.NodeMac isEqual:nodeMac])
        {
            zigbee = obj;
            isExist = YES;
        }
    }
    zigbee.NodeNetworkAddress = networkAddress;
    zigbee.NodeMac = nodeMac;
    zigbee.realMac = realMac;
    NSString *parentNetworkAddress = [[NSString alloc] init];
    parentNetworkAddress = [[values substringWithRange:NSMakeRange(22, 4)] uppercaseString];
    zigbee.ParentNetworkAddress = parentNetworkAddress;
    zigbee.NodeType = [values substringWithRange:NSMakeRange(1, 1)];
    if([zigbee.NodeType isEqualToString:@"C"])
    {
        zigbee.nodeLevel = 1;
    }else if([zigbee.NodeType isEqualToString:@"E"]){
        zigbee.nodeLevel = 3;
    }else if([zigbee.NodeType isEqualToString:@"R"]){
        zigbee.nodeLevel = 2;
    }
    NSMutableString *parentMac = [[NSMutableString alloc] init];
    [parentMac appendString:[[values substringWithRange:NSMakeRange(26,2)] uppercaseString]];
    [parentMac appendString:@":"];
    [parentMac appendString:[[values substringWithRange:NSMakeRange(28,2)] uppercaseString]];
    [parentMac appendString:@":"];
    [parentMac appendString:[[values substringWithRange:NSMakeRange(30,2)] uppercaseString]];
    [parentMac appendString:@":"];
    [parentMac appendString:[[values substringWithRange:NSMakeRange(32,2)] uppercaseString]];
    [parentMac appendString:@":"];
    [parentMac appendString:[[values substringWithRange:NSMakeRange(34,2)] uppercaseString]];
    [parentMac appendString:@":"];
    [parentMac appendString:[[values substringWithRange:NSMakeRange(36,2)] uppercaseString]];
    [parentMac appendString:@":"];
    [parentMac appendString:[[values substringWithRange:NSMakeRange(38,2)] uppercaseString]];
    [parentMac appendString:@":"];
    [parentMac appendString:[[values substringWithRange:NSMakeRange(40,2)] uppercaseString]];
    zigbee.ParentNodeMac = parentMac;
    NSString *currectAlterState = [[values substringWithRange:NSMakeRange(43,1)] uppercaseString];
    if(![zigbee.AlterState isEqualToString:currectAlterState]){
        zigbee.AlterState = [[values substringWithRange:NSMakeRange(43,1)] uppercaseString];
    }
    zigbee.isArm = [[values substringWithRange:NSMakeRange(44,1)] uppercaseString];
    
    
    if([parentNetworkAddress isEqualToString:@"0000"] && !isCoordinator)
    {
        isCoordinator = YES;
        ZigbeeModel *coordinator = [[ZigbeeModel alloc]init];
        coordinator.NodeType = @"C";
        coordinator.AlterState = @"R";
        coordinator.NodeMac = parentMac;
        coordinator.realMac = realMac;
        coordinator.NodeNetworkAddress = parentNetworkAddress;
        [_zigbeeArray addObject:coordinator];
    }
    if(!isExist) {
        [zigbee addObserver:self forKeyPath:@"AlterState" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"updateNodeState"];
        [_zigbeeArray addObject:zigbee];
    }else{
        isExist = NO;
    }
    NSString *newcount = [NSString stringWithFormat:@"%lu",[_zigbeeArray count]];
    if (![newcount isEqualToString:_cbHelper.arrayCount]){
        _cbHelper.arrayCount = [NSString stringWithFormat:@"%lu",(unsigned long)[_zigbeeArray count]];
    }
    [_zigbeeArray sortUsingComparator:^NSComparisonResult(__strong id obj1,__strong id obj2){
        return [obj1 nodeLevel] > [obj2 nodeLevel];
    }];
    [_nodeTableView reloadData];
    [self hasAlarm:_zigbeeArray];
    _cbHelper._zigbees = self.zigbeeArray;
}

-(void)createNodeAndChilde:(NSMutableArray*) nodes
{
    NSString *json;
    for(ZigbeeModel *obj in nodes)
    {
        [obj createDictionary];
    }
    for(ZigbeeModel *obj in nodes)
    {
        for(ZigbeeModel *childe in nodes){
            if([obj.NodeNetworkAddress isEqualToString:childe.ParentNetworkAddress])
            {
                //[childe createDictionary];
                [obj.childrenList addObject:childe.nodeDict];
            }
        }
    }
    for(ZigbeeModel *obj in nodes)
    {
        if([obj.NodeType isEqualToString:@"C"])
        {
            json = [obj.nodeDict JSONString];
        }
    }
    NSLog(@"%@",json);
}

//-(void)alarmPlay:(NSMutableArray*) models
//{
//    dispatch_async(dispatch_get_global_queue(0,0), ^{
//    //BOOL isAlarm = false;
//        NSInteger R_count = 0;
//        for(ZigbeeModel *obj in models)
//        {
//            if([obj.AlterState isEqualToString:@"R"] || [obj.AlterState isEqualToString:@"N"] || [obj.AlterState isEqualToString:@"ZC"])
//            {
//                R_count++;
//            }
//        }
//        if(R_count < [models count])
//        {
//            [self.alarm play];
//            [self registerLocalNotification:@"顺顺入侵啦"];
//        }else{
//            [self.alarm stop];
//        }
//    });
//}

-(void)alarmPlay:(BOOL) isAlarm
{
    dispatch_async(dispatch_get_global_queue(0,0), ^{
        //BOOL isAlarm = false;
        if(isAlarm)
        {
            [self.alarm play];
            
        }else{
            [self.alarm stop];
        }
    });
}


-(void)hasAlarm:(NSMutableArray*) models
{
    NSInteger R_count = 0;
    for(ZigbeeModel *obj in models)
    {
        if([obj.AlterState isEqualToString:@"A"])
        {
            R_count++;
        }
    }
    if(R_count>0)
    {
        if(_cbHelper.AlarmCount != R_count){
            _cbHelper.AlarmCount = R_count;
        }
        if([UIApplication sharedApplication].applicationState != UIApplicationStateBackground)
        {
            [self alarmPlay:YES];
            if(!_notificationTimer){
                [_notificationTimer invalidate];
                isTimerStart = NO;
            }
        }else{
            if (!_notificationTimer) {
                NSLog(@"Timer register");
                _notificationTimer = [NSTimer scheduledTimerWithTimeInterval:15.0
                                                                      target:self
                                                                    selector:@selector(alarmNotification)
                                                                    userInfo:nil
                                                                     repeats:YES];
                [[NSRunLoop currentRunLoop] addTimer:_notificationTimer forMode:NSDefaultRunLoopMode];
                isTimerStart = YES;
            }
            if(_notificationTimer != nil && isTimerStart == NO)
            {
                [[NSRunLoop currentRunLoop] addTimer:_notificationTimer forMode:NSDefaultRunLoopMode];
                isTimerStart = YES;
            }
        }
    }else{
        if(_cbHelper.AlarmCount != R_count){
            _cbHelper.AlarmCount = R_count;
        }
        if(!_notificationTimer){
            [_notificationTimer invalidate];
            isTimerStart = NO;
        }
        [self alarmPlay:NO];
    }

}

-(void)alarmNotification
{
    if([UIApplication sharedApplication].applicationState == UIApplicationStateBackground && _cbHelper.AlarmCount != 0)
    {
        [self registerLocalNotification:@"入侵警报！入侵警报！"];
    }
}

-(NSString*)currectTime
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss  "];
    NSString *dateTime = [dateFormatter stringFromDate:[NSDate date]];
    return dateTime;
}

- (void)registerLocalNotification:(NSString*)alertBody {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 设置触发通知的时间
    //NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
    //NSLog(@"fireDate=%@",fireDate);
    
    //notification.fireDate = fireDate;
    // 时区
    notification.timeZone = [NSTimeZone defaultTimeZone];
    // 设置重复的间隔
    notification.repeatInterval = kCFCalendarUnitSecond;
    
    // 通知内容
    notification.alertBody = alertBody;
    notification.applicationIconBadgeNumber = 1;
    // 通知被触发时播放的声音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知参数
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"开始学习iOS开发了" forKey:@"key"];
    notification.userInfo = userDict;
    
    // ios8后，需要添加这个注册，才能得到授权
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    } else {
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    }
    
    // 执行通知注册
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

/**
 * 设置白色状态栏
 */
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}


@end
